//
//  M4NetworkResult.swift
//  M4
//
//  Created by YuChuang on 2024/8/7.
//

import Foundation
import Moya
import KakaJSON
import Alamofire


struct M4NetworkResultModel: Convertible {
    var code: Int = 0
    var message: String?
    var data: Any?
}

private var netAlert: M4NetworkAlertView?

extension Result where Success: Response, Failure == MoyaError {
    func M4mapNetworkResult() -> M4NetworkResultModel {
        switch self {
        case .success(let response):
            if M4NetworkAlertView.M4AlertInKeywindow() != nil {
                M4NetworkAlertView.M4AlertInKeywindow()?.M4AlertViewHidden()
            }
            do {
                guard let json = try response.mapJSON() as? [String: Any] else {
                    let parseError = M4NetworkResultModel(code: -11, message: "The server returned not JSON data")
                    return parseError
                }
                print("-------- returnResultJson -------\n\(json)")
                let model = json.kj.model(M4NetworkResultModel.self)
                
                if model.code == 101 || model.code == 1002 {
                    M4UserDataManager.m4UserShare.M4Token = ""
                    M4UserDataManager.m4UserShare.M4AuditAccount = 0
                    if model.code == 101 { //未登录
                        AppDelegate.M4JumpLoginPage()
                    }
                    else {//挤下线
                        var alertTitle = "Su cuenta ha iniciado sesión en otro dispositivo, por favor intente de nuevo."
                        if model.message?.count != 0 {
                            alertTitle = model.message ?? alertTitle
                        }
                        let offAlert = UINib(nibName: "M4PublicAlertView", bundle: nil).instantiate(withOwner: self).last as? M4PublicAlertView
                        offAlert?.m4updateAlertUI(title: alertTitle, firstText: "Confirmar", secondText: "")
                        offAlert?.M4AlertFirstBlock = {
                            AppDelegate.M4JumpLoginPage()
                        }
                        offAlert?.M4AlertViewShow()
                    }
                    return M4NetworkResultModel(code: model.code, message: "")
                }
                
                return model
            } catch {
                
                return M4NetworkResultModel(code: -33, message: "Parsing error:\(error.localizedDescription)")
            }
        case .failure(let error):
            let moyaError = error.errorUserInfo[NSUnderlyingErrorKey] as? AFError
            let nsError = moyaError?.asAFError?.underlyingError as NSError?
            if nsError?.code == NSURLErrorTimedOut ||
                nsError?.code == NSURLErrorNotConnectedToInternet ||
                nsError?.code == NSURLErrorNetworkConnectionLost {
                DispatchQueue.main.async {
                        M4NetworkAlertView.shared.showOnce()
                }
                return M4NetworkResultModel(code: -44, message: "")
            }
            else {
                return M4NetworkResultModel(code: -55, message: "Por favor verifique su conexión de red")
            }
        }
    }
    
}
